<?php

function EventRunBySource($section,$source,$passthrough,$desc=""){
$sql="select EventSourceID from xAP_EventSource where  Section='".dbesc($section)."' and  Source='".dbesc($source)."'";

	$row=dbquery($sql);

	if(count($row)==0){

		$sql="insert into xAP_EventSource (Section,Source,SourceDesc,LastPassThrough) VALUES 
		('".dbesc($section)."','".dbesc($source)."','".dbesc($desc)."','".dbesc(serialize($passthrough))."')";
		

		dbexec($sql);
		
		xAPLog("Event","Created ".$section." ".$source,"");
	}
	else
	{
		foreach($row as $value){
			EventRunBySourceID($value["EventSourceID"],$passthrough);
		}	
	
	//save last event.  Useful for the designer
		$sql="update xAP_EventSource set
		LastPassThrough='".dbesc(serialize($passthrough))."' 
		where  Section='".dbesc($section)."' and  Source='".dbesc($source)."'";
		dbesc($sql);
	}
}

function EventRunBySourceID($sourceid,$passthrough){
xAPLog("EVENT","Running Event ".$sourceid,"");
$sql="select EventID from xAP_EventLink where  EventSourceID='".dbesc($sourceid)."' and Active=1";
	$row=dbquery($sql);

	foreach($row as $value){

			EventRun($value["EventID"],$passthrough);

	}


}
function EventRun($eventid,$passthrough){
	$sql="select active from xAP_Event where EventID='".dbesc($eventid)."'";
	$event=dbquery($sql);

	// is event active
	if ($event[0]["active"]==1){
			$sql="select * from xAP_EventElement where EventID='".dbesc($eventid)."'";
			$row=dbquery($sql);

			foreach($row as $value){

					EventRunElement($value,$passthrough);
					
			}
		}
}

function EventRunElement($eventelement,$passthrough){
	if ($eventelement["EventLibraryID"]>0){
		$sql="Select Body,Class from xAP_EventLibrary where EventLibraryID=".$eventelement["EventLibraryID"];
		$e=dbquery($sql);
		//replace *Data1-8*
		for($i=1;$i<9;$i++){
			$e[0]["Body"]=str_replace("*Data".$i."*",$eventelement["Data".$i],$e[0]["Body"]);
		}
		xAPSend($e[0]["Class"],$e[0]["Body"],$eventelement["Target"]);
	}
}


function EventDeleteByLink($linkid){
$sql="select EventID from xAP_Event where LinkID='".dbesc($linkid)."'";
	$row=dbquery($sql);

	foreach($row as $value){

			EventDelete($value["EventID"]);

	}

}
function EventDelete($eventid){
	// delete event and all it's elements
	dbexec("delete from xAP_EventElement where EventID=".intval($eventid));
	dbexec("delete from xAP_Event where EventID=".intval($eventid));
	dbexec("delete from xAP_EventLink where EventID=".intval($eventid));
	xAPLog("Event","Delete ".$eventid,"");
}




?>